<template>
  <basic-container>

    <avue-crud
      ref="crud"
      v-model="templateForm"
      :table-loading="Loading"
      :page="page"
      :data="tableData"
      :option="tableOption"
      @on-load="onLoad"
      @refresh-change="onLoad"
      @row-save="handleSave"
      @row-update="handleUpdate"
      :before-close="beforeClose"
      :before-open="beforeOpen"
    >
      <template slot-scope="{type,size,row}" slot="menu">
        <el-button @click.stop="handleEdit(row)" icon="el-icon-edit" :size="size" :type="type">编辑</el-button>
        <el-button @click.stop="rowDel(row)" icon="el-icon-delete" :size="size" :type="type">删除</el-button>
        <el-button type="text" icon="el-icon-view" size="small" @click.stop="preview(row)">预览</el-button>
        <el-button type="text" icon="el-icon-view" size="small" @click.stop="downLoad(row)">下载</el-button>
      </template>
      <template slot-scope="{}" slot="imgUrlLabel">
        <span style="color:#F56C6C;margin-right: 4px;">*</span><span>模板文件&nbsp;&nbsp;</span>
      </template>
      <template slot-scope="{row}" slot="imgUrlForm">
        <span v-if="isEdit">{{row.originalName}}</span>
        <el-upload
          class="upload-demo"
          ref="upload"
          :limit="1"
          :headers="headers"
          :data="uploadData"
          :action="url"
          :auto-upload="false"
          :on-success="successUpload"
          :on-exceed="moreFilesTip"
          :on-change="changeFile"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        </el-upload>
      </template>
    </avue-crud>
    <el-dialog class="avue-dialog avue-crud__dialog" custom-class="dialog-width" append-to-body title="预览" :visible.sync="previewVisible">
      <div style="text-align: center;margin-bottom: 20px;">
        <img style="max-width: 600px;" :src="imgUrl" v-if="pictureTypes.indexOf(tempType) > -1">
        <video :src="imgUrl" controls="controls" v-if="videoTypes.indexOf(tempType) > -1"></video>
      </div>

      <!--<video :src="imgUrl" controls="controls"></video>-->
    </el-dialog>
  </basic-container>
</template>
<script>

function createList(){
  return [
  {
    "name":"公文报批模板",
    'type':'excel',
    'size':'200KB',
    "desc":"公文报批模板",
    "uploadTime":"2021-5-21 10:23:25",
    "uploader":"admin"
  },
  {
    "name":"模板A",
    "desc":"模板A",
    'type':'excel',
    'size':'200KB',
    "uploadTime":"2021-5-21 14:12:36",
    "uploader":"admin"
  }
]
}
import website from '@/config/website';
import {Base64} from 'js-base64';
import {getToken} from '@/util/auth';
import {
  getTemplateList,
  saveTemplate,
  updateTemplate,
  removeTemplate,
  saveUrl,
  updateUrl,
  downUrl,
  downLoadTemplate
} from '@/api/dataMaintenance/fileTemplate';
export default {
  data(){
    return {
      // .MPG .MPEG .MPE .DAT .VOB .ASF .3GP .MP4 .ogg .ogv webm
      pictureTypes:['BMP','bmp','JPG','jpg','JPEG','jpeg','PNG','png','GIF','gif'],
      videoTypes: ['MPG','mpg','MPEG','mpeg','MPE','mpe','DAT','dat','VOB','vob','ASF','asf','3GP','3gp','MP4','mp4','OGG','ogg','OGV','ogv','WEBM','webm'],
      Loading:false,
      isEdit: false,
      fileList:[],
      previewVisible:false,
      tempType:'',
      imgUrl:'',
      url:'',
      saveUrl:saveUrl,
      updateUrl:updateUrl,
      downUrl:downUrl,
      uploadData: {
        attach:''
      },
      headers:{},
      templateForm:{},
      tableData: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      tableOption: {
        //height: 'auto',
        //calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,
        editBtn: false,
        //addBtn: false,
        // viewBtn: true,
        delBtn: false,
        // menuWidth: 350,
        dialogClickModal: false,
        menuWidth: 180,
        column: [
          {
            label: '模板名称',
            prop: 'name',
            width: 140,
            display: false,
          },
          {
            label: '文件类型',
            prop: 'temType',
            type:'select',
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=attach_type',
            display: false
          },
          {
            label: '文件限额大小(KB)',
            prop: 'limitSize',
            display: false
          },
          {
            label: '描述',
            prop: 'descr',
            display: false
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            type: "date",
            format: "yyyy-MM-dd hh:mm:ss",
            width: 140,
            display: false
          },
          {
            label: '操作人',
            prop: 'createUserName',
            display: false
          }
        ],
        group: [
          {
            column: [
              {
                label: "模板名称",
                prop: "name",
                span: 24,
                rules: [{
                  required: true,
                  message: "请输入名称",
                  trigger: "blur"
                }]
              },
              {
                label: "模板类型",
                prop: "temType",
                props: {
                  label: "dictValue",
                  value: "dictKey"
                },
                span: 24,
                type:'select',
                dicUrl: '/api/blade-system/dict/dictionary?code=attach_type',
                // dicData: [
                //   {
                //     label:'图片',
                //     value:'picture'
                //   },
                //   {
                //     label:'视频',
                //     value:'video'
                //   }
                // ],
                rules: [{
                  required: true,
                  message: "请选择模板类型",
                  trigger: "change"
                }]
              },
              {
                label: "文件限额",
                prop: "limitSize",
                tip:'KB',
                span: 24,
                type:'number',
                rules: [{
                  required: true,
                  message: "请输入文件限额",
                  trigger: "blur"
                }]
              },
              {
                label: '模板文件',
                prop: 'imgUrl'
              },
              {
                label: "描述",
                prop: "descr",
                type: "textarea",
                minRows: 2,
                span: 24,
              },
            ]
          }
          ]
      },
      file:null
    }
  },
  mounted() {
    this.setHeader();
  },
  methods: {
    beforeOpen(done,type) {
      if(type === 'add') {
        this.isEdit = false;
      } else {
        this.isEdit = true;
      }
      done();
    },
    beforeClose(done) {
      this.file = null;
      this.fileList = [];
      done();
    },
    changeFile(file, fileList) {
      console.log(file)
      this.file = file;
      this.isEdit = false;
    },
    moreFilesTip() {
      this.$message.error('只能选择一个文件');
    },
    setHeader() {
      this.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
      //让每个请求携带token
      this.headers[website.tokenHeader] = 'bearer ' + getToken();
    },
    onLoad(){
      this.getTemplateList();
      //this.tableData = createList();
    },
    getTemplateList() {
      this.Loading = true;
      getTemplateList({
        current: this.page.currentPage,
        size: this.page.pageSize
      }).then( res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.tableData = data.records;
        this.Loading = false;
      }).catch( error => {
        this.Loading = false;
      });
    },
    handleEdit(row) {
      this.fileList = [];
      this.fileList.push({
        'name':row['originalName']
      })
      this.$nextTick(function () {
        this.$refs.crud.rowEdit(row);
      })

    },
    handleUpdate(row, index, done, loading) {
        let obj = {
          id:row['id'],
          name:row['name'],
          temType: row['temType'],
          limitSize: row['limitSize'],
          descr: row['descr']
        };
        this.uploadData.attach = JSON.stringify(obj);

      if(this.$refs.upload.uploadFiles.length === 0 || this.$refs.upload.uploadFiles[0]['raw'] === undefined ) {
        const formData = new FormData();
        formData.append('attach',this.uploadData.attach);
        updateTemplate(formData).then( res => {
          this.getTemplateList();
          done();
        });
      } else {
        this.url = this.updateUrl;
        this.$nextTick(function () {
          let obj = {
            id:row['id'],
            name:row['name'],
            temType: row['temType'],
            limitSize: row['limitSize'],
            descr: row['descr']
          };
          this.uploadData.attach = JSON.stringify(obj);
          const formData = new FormData();
          formData.append('attach',this.uploadData.attach);
          formData.append('file', this.file.raw, this.file.name);
          updateTemplate(formData).then( res => {
            this.successUpload();
            done();
          });
          //this.$refs.upload.submit();
          done();
        });
      }


      // updateTemplate(obj).then( res => {
      //   this.getTemplateList();
      //   this.$message({
      //     type: "success",
      //     message: "操作成功!"
      //   });
      //   done();
      // }).catch( error => {
      //   loading();
      // });
    },
    handleSave(row,done,loading) {

      if(this.$refs.upload.uploadFiles.length === 0 ) {
        this.$message.error('请选择文件');
        loading()
        return;
      }

      this.url = this.saveUrl;
      this.$nextTick(function () {
        let obj = {
          name:row['name'],
          temType: row['temType'],
          limitSize: row['limitSize'],
          descr: row['descr']
        };
        this.uploadData.attach = JSON.stringify(obj);
        const formData = new FormData();
        formData.append('attach',this.uploadData.attach);
        formData.append('file', this.file.raw, this.file.name);
        saveTemplate(formData).then( res => {
          this.successUpload();
          done();
        });
      })
    },
    successUpload(res) {
      this.$message({
        type: "success",
        message: "操作成功!"
      });
      this.getTemplateList();
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeTemplate(row.id);
        })
        .then(() => {
          this.getTemplateList();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    downLoad(row){
      //window.open(`${this.downUrl}?id=${row['id']}`);
      downLoadTemplate({id:row['id']}).then( res => {
        const content = res.data
        const blob = new Blob([content])
        const file = row.originalName
        if ('download' in document.createElement('a')) {
          const elink = document.createElement('a')
          elink.download = file
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          this.imgUrl = URL.createObjectURL(blob);
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href)
          document.body.removeChild(elink)
        } else {
          navigator.msSaveBlob(blob, file)
        }
      });
    },
    preview(row) {
      this.tempType = row['temType'];
      downLoadTemplate({id:row['id']}).then( res => {
        const content = res.data
        const blob = new Blob([content])
        const file = row.originalName
        this.imgUrl = URL.createObjectURL(blob);
        this.previewVisible = true;
      });
    }
  }
}
</script>
